package com.standardoperationapp.bluetooth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.standardoperationapp.activity.BluetoothSetActivity;
import com.standardoperationapp.global.GlobalVaries;

import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

public class BluetoothManger {
//
    public static List<String> mPermissionList = new ArrayList<>();
     //蓝牙变量

    public static  BluetoothManager mBluetoothManager;
    public static BluetoothAdapter mBluetoothAdapter;
    public  static BluetoothGatt mBluetoothGatt;
    public  static BluetoothGattCharacteristic write_characteristic;
    public  static  BluetoothDevice currentOpeningdevice;
    public static Context blueContext;
    public static Handler blueHandler;
    private static BleLockParamInfo tmpl_bleLockParamInfo,mbleLockParamInfo;
    //标志位
public static boolean mIsDoCheckLockState =false;
    public static boolean mLockIsOpened=false;
    //常量

    public static final int PERMISSION_REQUEST_CODE = 10;
    public static final String TAG="Bluetooth";
  //  public final static String ACTION_GATT_CONNECTED = "com.nokelock..ACTION_GATT_CONNECTED";// 连接
    public final static int ACTION_GATT_CONNECTED =1000 ;// 连接
    public final static int ACTION_GATT_DISCONNECTED =1001;//断开连接
  //  public final static String ACTION_GATT_DISCONNECTED = "com.nokelock..ACTION_GATT_DISCONNECTED";// 断开
   // public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.nokelock..ACTION_GATT_SERVICES_DISCOVERED";// 发现服务
    public final static int  ACTION_GATT_SERVICES_DISCOVERED =1002;//发现服务

    public final static int  DISMISS_PROGRESS_DIALOG=500; //取消进度条
    public final static int  SHOW_PROGRESS_DIALOG=501; //显示进度条
    public final static int  UPDATE_WARNDIALOG =502;
    public final static int  SEND_OPEN_RECORD =503;
    public final static int OPEN_LOCK_FAIL=504;
    public final static int  CLOSE_LOCK=505;
    public final static int UPDATE_STATE =506;
    public static final int RECONNECT =507;
  //  public static final String ACTION_BLE_REAL_DATA = "com.nokelock..ACTION_BLE_REAL_DATA";//通知数据
    public static final int ACTION_BLE_REAL_DATA =1003;//通知数据
    public static final UUID TMPL_SERVICE_UUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    public static final UUID TMPL_Write_UUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    public static final UUID TMPL_Read_UUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
    public static final UUID TMPL_CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");

    private static final byte[] TMPL_EncryptKey = new byte[]{0x1D, 0x22, 0x45, 0x28};
    private static final byte TMPL_Key = 0x3E;
public static boolean reconnectFlag =false;
    public static long mLockOpenedtime =0;//开锁时间
    public static int counter=0;
    public static int mWorkModel = 0;//发现服务..mWorkModel:0=开锁，1=查询参数，2=设置参数
    public static boolean isStartScan =false;
    private static Object mSyncOpenLockObj = new Object();
    public static   List<BluetoothDevice> mbluetoothDeviceList = new ArrayList<BluetoothDevice>();
    @SuppressLint("MissingPermission")
    public static void resetBluetooth(){

        mBluetoothManager=null;
        mBluetoothAdapter=null;
        mBluetoothGatt=null;
        write_characteristic=null;
        blueContext=null;
        currentOpeningdevice=null;
        blueHandler=null;
        mLockIsOpened=false;
        mLockOpenedtime =0;
        counter=0;
        tmpl_bleLockParamInfo=null;
        mIsDoCheckLockState =false;
        mWorkModel = 0;
        mbleLockParamInfo=null;

    }
    public static void  initPermission( Activity activity) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 版本大于等于 Android12 时
            // 只包括蓝牙这部分的权限，其余的需要什么权限自己添加
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
        } else {
            // Android 版本小于 Android12 及以下版本
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            Log.e("syj","申请权限！");
        }
     //   mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
     //   mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
        if (mPermissionList.size() > 0) {
            ActivityCompat.requestPermissions(activity, mPermissionList.toArray(new String[0]), PERMISSION_REQUEST_CODE);
        }
    }
    @SuppressLint("MissingPermission")
    public static boolean initBluetooth(Context context, Handler handler,int ConnectCounter) {
        //mkey = com.tideen.core.ConfigHelper.getNodeBleLockKey();
        mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (null == mBluetoothAdapter){
            return false;
        }

        if (!mBluetoothAdapter.isEnabled()) {

            mBluetoothAdapter.enable();
        }
        blueContext=context;
        blueHandler =handler;
        ScanFilter.Builder scanfilterbuilder = new ScanFilter.Builder();
        //scanfilterbuilder.setServiceUuid(ParcelUuid.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"));
        ScanFilter filter = scanfilterbuilder.build();
        ScanSettings.Builder scanSettingsbuilder = new ScanSettings.Builder();
        scanSettingsbuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
        ScanSettings scanSettings = scanSettingsbuilder.build();
        return true;
    }
    @SuppressLint("MissingPermission")
    public static void startScan() {
        try {
            if (isStartScan)
                return;

            isStartScan = true;
            // mBluetoothAdapter.startLeScan(new UUID[]{RX_SERVICE_UUID,RX_CHAR_UUID,TX_CHAR_UUID},leScanCallback);
            // mBluetoothAdapter.startLeScan(leScanCallback);
            ScanFilter.Builder scanfilterbuilder = new ScanFilter.Builder();
            //scanfilterbuilder.setServiceUuid(ParcelUuid.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"));
            ScanFilter filter = scanfilterbuilder.build();
            ScanSettings.Builder scanSettingsbuilder = new ScanSettings.Builder();
            scanSettingsbuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
            ScanSettings scanSettings = scanSettingsbuilder.build();
            BluetoothManger.mbluetoothDeviceList.clear();
            mBluetoothAdapter.getBluetoothLeScanner().startScan(Collections.singletonList(filter), scanSettings, myScanCallback);
            //startMonitorBluetoothDiscover();
          //  Log.e(TAG, "OpenNokeBleLockHelper.start.hashCode=" + this.hashCode());
        } catch (Exception ee) {
            Log.e(TAG, ee.toString());
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    static ScanCallback myScanCallback = new ScanCallback() {
        @Override
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            //    Log.e(TAG,"BLEScanCallback.onScanResult callbackType="+callbackType);
            myonLeScan(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "BLEScanCallback.onScanFailed errorCode=" + errorCode);
        }
    };

    @SuppressLint("MissingPermission")
    private static synchronized void myonLeScan(BluetoothDevice bluetoothdevice, int rssi, byte[] scanRecord) {
        try {
            //Log.e(TAG,"Bluetooth Find:" + device.getName());
            //Log.e("TLock","Bluetooth Find:" + device.getName());

            @SuppressLint("MissingPermission")
            String devicename = bluetoothdevice.getName();
            if (TextUtils.isEmpty(devicename))
                return;
            Log.e(TAG, "Find Ble Device:" + devicename + "," + bluetoothdevice.getAddress());
//            if (!devicename.startsWith("TDL") && !devicename.startsWith("OK") && !devicename.startsWith("SGL") && !devicename.startsWith("TMPL")
//                    && !devicename.startsWith("TMOL")) {
//                return;
//            }

            synchronized (mSyncOpenLockObj) {
                if (!mbluetoothDeviceList.contains(bluetoothdevice)) {
                    mbluetoothDeviceList.add(bluetoothdevice);
                    //BleDevice bleDevice = new BleDevice(device, scanRecord, rssi);
                    //bleDeviceList.add(bleDevice);
                    Log.e(TAG, "Find Ble Lock:" + devicename + "," + bluetoothdevice.getAddress());
                    Log.e(TAG,"deviceList.size: "+Integer.toString(mbluetoothDeviceList.size()));

                    //停止扫描 连接

//                    if (!mAutoOpenDoor) {
//                        return;
//                    }else {
//                        openLock(bluetoothdevice);
//                    }

                }

            }
        } catch (Exception ee) {
            Log.e(TAG, ee.toString());
        }
    }

    @SuppressLint("MissingPermission")
    public static  void stopScan(){
        mBluetoothAdapter.getBluetoothLeScanner().stopScan(myScanCallback);
//        try {
//            Thread.sleep(1000);
//        } catch (Exception e) {
//        }
        isStartScan = false;
    }
    /**
     * 蓝牙链接
     *
     * @param address 执行链接的MAC地址
     * @return 是否连接成功
     */
    @SuppressLint("MissingPermission")
    public static boolean connectLock(Context context,Handler handler,final String address, boolean isreconnect) {
        GlobalVaries.curBattery = 0.0;
        if (mBluetoothAdapter == null || address == null) {
            Log.e("Bluetooth", "BluetoothAdapter not initialized or unspecified address.");
          //syj 更改  return false;
            mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = mBluetoothManager.getAdapter();
            if (null == mBluetoothAdapter){
                Log.e("Bluetooth","BluetoothAdapter is null");
                return false;
            }

            if (!mBluetoothAdapter.isEnabled()) {

                mBluetoothAdapter.enable();
            }
            blueContext=context;
            blueHandler=handler;

        }

        if (isreconnect) {
            // startShowProgressDialog("请等待");
            Log.e("Bluetooth", "reconnect");

        }
        if (mBluetoothGatt != null) {

            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
        }
        mBluetoothAdapter.getBluetoothLeScanner().stopScan(myScanCallback);
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
//
        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.e("Bluetooth", "Device not found.  Unable to connect.");
            return false;
        }
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mBluetoothGatt = device.connectGatt(context, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
                Log.e(TAG, "SDK1");
            } else {
                Log.e(TAG, "SDK2");
                mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
            }
        } catch (IllegalArgumentException exception) {
                Log.e(TAG, "Device not found with provided address.  Unable to connect.");
                return false;
            }

      //  mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
        Log.e("Bluetooth", "Trying to create a new connection.");
        //mBluetoothDeviceAddress = address;
        if (mBluetoothGatt == null)
        {
            Log.e("Bluetooth", "创建gatt 连接失败.");
            return false;
        }


        return true;
    }

    public static final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        /**
         * 连接状态
         */
        @Override
        @SuppressLint("MissingPermission")
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            try {
                Log.e(TAG,"onConnectionStateChange "+newState);
                Message msg = new Message();
                if (newState == BluetoothProfile.STATE_CONNECTED) {// 连接成功
                   // onBluetoothGattCallback(ACTION_GATT_CONNECTED);
                    msg.what =ACTION_GATT_CONNECTED;
                    blueHandler.sendMessage(msg);
                    currentOpeningdevice = gatt.getDevice();//syj  add
                    boolean result = mBluetoothGatt.discoverServices();
                    Log.e(TAG, "Lock Start discoverServices.Result=" + result);
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {// 断开连接
                    // gatt.close();
                    msg.what =ACTION_GATT_DISCONNECTED;
                    blueHandler.sendMessage(msg);
                  //  onBluetoothGattCallback(ACTION_GATT_DISCONNECTED);
                }
            } catch (Exception ee) {
                Log.e(TAG, "onConnectionStateChange erro "+ee.toString());
            }
        }

        /**
         * 发现服务
         */
        @SuppressLint("MissingPermission")
        @Override
        public  void onServicesDiscovered(BluetoothGatt gatt, int status) {
            try {
                Log.e(TAG, "Lock onServicesDiscovered status= " + status);
                if (status == BluetoothGatt.GATT_SUCCESS) {


                    //获取服务的对象并判断是否为空
                    BluetoothGattService service = gatt.getService(TMPL_SERVICE_UUID);
                    if (null == service) {
                        Log.e(TAG, "根据SERVICE_UUID获取服务为null");
                        return;
                    }
                    //获取写入特征值和通知特征值的对象并判断是否为空
                    BluetoothGattCharacteristic read_characteristic = service.getCharacteristic(TMPL_Read_UUID);
                    //开启通知属性

                    if (gatt.setCharacteristicNotification(read_characteristic, true)) {
                        //List<BluetoothGattDescriptor> descriptorlist = read_characteristic.getDescriptors();
                        BluetoothGattDescriptor descriptor = read_characteristic.getDescriptor(TMPL_CCCD);
                        if (null != descriptor) {
                            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                            gatt.writeDescriptor(descriptor);
                        }
                    }
                    write_characteristic = service.getCharacteristic(TMPL_Write_UUID);


                    if (null == write_characteristic) {
                        Log.e(TAG, "没有获取到蓝牙的读写属性。");
                        return;
                    }

                    //发送广播通知前端
                    Message msg =new Message();
                    msg.what =ACTION_GATT_SERVICES_DISCOVERED;
                    blueHandler.sendMessage(msg);
                   // onBluetoothGattCallback(ACTION_GATT_SERVICES_DISCOVERED);
                } else {
                    Log.e(TAG, "OpenNokeBleLockHelper.onServicesDiscovered status= " + status);
                }

            } catch (Exception ee) {
                Log.e(TAG, "onServicesDiscovered erro "+ee.toString());
            }
        }

        /**
         * 通知的回调。。蓝牙设备发送过来数据
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
           // onBluetoothGattCallback(ACTION_BLE_REAL_DATA, characteristic.getValue());
            Message msg=new Message();
            msg.what =ACTION_BLE_REAL_DATA;
            msg.obj =characteristic.getValue();
            blueHandler.sendMessage(msg);
        }

        /**
         * 通知的回调。。蓝牙设备发送过来数据
         */
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
          //  onBluetoothGattCallback(ACTION_BLE_REAL_DATA, characteristic.getValue());
            Message msg=new Message();
            msg.what =ACTION_BLE_REAL_DATA;
            msg.obj =characteristic.getValue();
            blueHandler.sendMessage(msg);

        }
    };

    public static BluetoothDevice getCurrentOpeningdevice() {
        return currentOpeningdevice;
    }

    @SuppressLint("MissingPermission")
    public static void TMPL_processData(byte[] data) throws Exception {
        String getData = ByteConvert.bytesToHex(data); //CDRYTLock_Utils.bytes2String(data);
        Log.e(TAG, "TMPL解析数据:" + getData);
        Message msg = new Message();
        if (data.length < 3 || data[0] != 0x7D || data[1] != 0x7D) {
            return;
        }
        //syj  stopCaptureTimeCount();
        if (data.length >= 16 && data[4] == 0x50 && data[13] == 0x20) {//读取UTC时间
            int utctime = ByteConvert.byte2Int(new byte[]{data[9], data[10], data[11], data[12]});
//            Calendar nowtime=Calendar.getInstance();
//            nowtime.clear();
//            nowtime.set(1970,1,1,0,0,0);
//            nowtime.add(Calendar.SECOND,utctime);
//            Log.e(TAG,"TMPL锁UTC:"+utctime+","+Util.formatDateTime( nowtime.getTime()));
            TMPL_SendOpenLockCMD(utctime + 30);
            //TMPL_SendUpGradeCMD();
        } else if (data.length == 16 && data[4] == 0x50 && data[13] == 0x30) {//开锁回复
//            int utctime=byte2Int(new byte[]{data[9],data[10],data[11],data[12]});
//            Calendar nowtime=Calendar.getInstance();
//            nowtime.clear();
//            nowtime.set(1970,1,1,0,0,0);
//            nowtime.add(Calendar.SECOND,utctime);
//            Log.e(TAG,"TMPL开锁UTC:"+utctime+","+Util.formatDateTime( nowtime.getTime()));

//   syj          msg.what =DISMISS_PROGRESS_DIALOG;
//            blueHandler.sendMessage(msg);

            if (data[14] == 0x00) {//锁状态是开
                mLockIsOpened = true;
                GlobalVaries.openTime=getCurtimeStr();
                mLockOpenedtime = System.currentTimeMillis();
                GlobalVaries.UpdateWarnFlag =true;
               msg.what =BluetoothManger.UPDATE_STATE;
               blueHandler.sendMessage(msg);
                TMPL_startCheckLockSeal();
            } else {

                msg.what =OPEN_LOCK_FAIL;
                blueHandler.sendMessage(msg);
                Log.e(TAG, "开锁失败！");


            }
        } else if (data.length > 22 && data[4] == 0x50 && data[13] == 0x10) {//查询锁状态回复
            //7d 7d 2f 00 50 f1 03 00 21 64 f1 f7 46 10 20 23 08 16 00 12 01 aa 11 20 1c 14 3839383630344439323632334430333336363435 03
//            int utctime=byte2Int(new byte[]{data[9],data[10],data[11],data[12]});
//            Calendar nowtime=Calendar.getInstance();
//            nowtime.clear();
//            //nowtime.set(1970,1,1,0,0,0);
//            nowtime.add(Calendar.SECOND,utctime);
//            Date date=new Date(utctime*1000);

            //Log.e(TAG,"TMPL开锁UTC:"+utctime+","+Util.formatDateTime( nowtime.getTime()));
            int powerv = ByteConvert.byte2Int(new byte[]{0, 0, data[20], data[21]});

            Log.e(TAG, "电池： " + Integer.toString(powerv));
            double battery= GetPowerPercent_HHD(powerv / 100.0d);
            Log.e(TAG, "电池结果： " + Double.toString(battery));
            //  int battery = (int)d;

            GlobalVaries.curBattery = battery;


            int state0 = data[22] & 0x01;//锁梁开关：0=锁杆已拉开，1=锁杆未拉开或已按下，电机不一定锁上
            int state1 = data[22] & 0x02;//滚珠开关，用于判断锁体放置方向：0 = 锁体正向放置，1 = 锁体反向放置
            int state2 = data[22] & 0x04;//霍尔开关：0=锁杆已吸住。4=锁杆未吸住，
            int state3 = data[22] & 0x08;//电机开关：0=槽型光电开关未被遮挡（未上锁），8= 槽型光电开关被遮挡（已上锁）
            int state4 = data[22] & 0x10;//防拆开关，用于防拆。0 = 防拆开关正常，1 = 锁面盖已被拆开
            String simiccid = "";
            int simlength = 0;
            if (data.length > 46) {
                simlength = ByteConvert.byte2Int(new byte[]{0, 0, 0, data[25]});
                simiccid = new String(data, 26, simlength, "ASCII");
//                if (tmpl_bleLockParamInfo != null && mOnBleLockStateChangedListener != null)
//                    tmpl_bleLockParamInfo.SIMICCID_Value = simiccid;
//                //syj      mOnBleLockStateChangedListener.onGetLockParam(tmpl_bleLockParamInfo);
            }
            Log.e(TAG, "TMPL锁状态：锁梁开关=" + state0 + ",倾斜开关=" + state1 + ",霍尔开关=" + state2 + ",电机开关=" + state3 + ",防拆开关=" + state4 +
                    (data.length > 24 ? (",4G开关=" + ByteConvert.byteToInt(data[23]) + ",4G信号强度=" + ByteConvert.byteToInt(data[24])) : "") + ",电压=" + powerv + ",SIM=" + simiccid);
            if (!mLockIsOpened) return;
            ////读锁状态
            if (getCurrentOpeningdevice().getName().startsWith("TMOL")) {//TMOL是嵌入式带把手门锁，TMPL是挂锁
                if (state0 == 0 && state3 == 8) {//state3表示霍尔开关。。state0表示锁舌
                    //showcdtestMessage("得到状态:关");
                    mLockIsOpened = false;
                    TMPL_stopCheckLockSeel();
                    disconnectLock();
                } else //if (state3 == 0)
                {
                    // showcdtestMessage("得到状态:开");
                    if (mIsDoCheckLockState) {
                        // syj showMessage("锁没有关闭！");
                        Log.e(TAG,"锁没有关闭");
                    }
                }
            } else {
                if (state0 == 1 && state3 == 8) {
                    //showcdtestMessage("得到状态:关");
                    mLockIsOpened = false;
                    TMPL_stopCheckLockSeel();
                    GlobalVaries.closeTime=getCurtimeStr();
                    Message msg1 = new Message();
                    msg1.what=SEND_OPEN_RECORD;
                    blueHandler.sendMessage(msg1);
                    disconnectLock();
                } else //if (state0==0&&state3 == 0)
                {
                    Log.e(TAG,"得到状态:开！");
                   // showcdtestMessage("得到状态:开");
                    if (mIsDoCheckLockState) {
                        Log.e(TAG,"锁没有关闭！");
                    }
                }
            }
            mIsDoCheckLockState = false;
           // msg.what=DISMISS_PROGRESS_DIALOG;
          //  blueHandler.sendMessage(msg);
        } else if (data.length > 19 && data[4] == 0x50 && data[13] == 0x23) {//读取设置Ip参数回应
            // String ip = ByteConvert.byteToInt(data[14]) + "." + ByteConvert.byteToInt(data[15]) + "." + ByteConvert.byteToInt(data[16]) + "." + ByteConvert.byteToInt(data[17]);
            String ip = ByteConvert.byteToInt(data[14]) + "." + ByteConvert.byteToInt(data[15]) + "." + ByteConvert.byteToInt(data[16]) + "." + ByteConvert.byteToInt(data[17]);
            int port = ByteConvert.byte2Int(new byte[]{0, 0, data[18], data[19]});
            Log.e(TAG, "TMPL锁Param:IP=" + ip + ",Port=" + port);
            tmpl_bleLockParamInfo = new BleLockParamInfo();
            tmpl_bleLockParamInfo.ServerIP_Value = ip;
            tmpl_bleLockParamInfo.ServerPort_Value = String.valueOf(port);
            TMPL_ReadLockParam_APN();
        } else if (data.length > 15 && data[4] == 0x50 && data[13] == 0x25) {//读取、设置APN
            String apnname = new String(data, 14, data.length - 15, "UTF-8");
            // Log.e(TAG,"TMPL锁Param:apnname="+apnname);
            if (tmpl_bleLockParamInfo != null)
                tmpl_bleLockParamInfo.APN1Name_Value = apnname;
//   syj        msg.what =DISMISS_PROGRESS_DIALOG;
//           blueHandler.sendMessage(msg);

           /* if (mWorkModel == 2 && mOnBleLockStateChangedListener != null)
                mOnBleLockStateChangedListener.onSetLockParamResult(true);
            else*/ if (mWorkModel == 1)//查参数
            {
                TMPL_SendGetLockStateCMD();
            }
        } else if (data.length > 19 && data[4] == 0x50 && data[13] == 0x26) {//读取设置服务器地址和端口参数回应
            byte ipflag = data[14];
            String ip = "";
            if (ipflag == 0x00)
                ip = ByteConvert.byteToInt(data[15]) + "." + ByteConvert.byteToInt(data[16]) + "." + ByteConvert.byteToInt(data[17]) + "." + ByteConvert.byteToInt(data[18]);
            else
                ip = new String(data, 19, data.length - 22);
            int port = ByteConvert.byte2Int(new byte[]{0, 0, data[data.length - 3], data[data.length - 2]});
            // Log.e(TAG,"TMPL锁Param:IP="+ip+",Port="+port);
            tmpl_bleLockParamInfo = new BleLockParamInfo();
            tmpl_bleLockParamInfo.ServerIP_Value = ip;
            tmpl_bleLockParamInfo.ServerPort_Value = String.valueOf(port);

            if (mWorkModel == 2)//写参数
            {
                TMPL_WriteLockParam_APN();
            } else {
                TMPL_ReadLockParam_APN();
            }
        }
    }
    @SuppressLint("MissingPermission")
    public static void disconnectLock() {

        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            mLockIsOpened = false;
        }
        resetBluetooth();
    }
    public static void TMPL_WriteLockParam_APN() {
        if (mbleLockParamInfo == null) return;
        // byte[] cmdbytes=new byte[]{0x7D,0x7D,0x0F,TMPL_Key,0x50,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,0x5F,0x00,0x00,0x00,0x25,0x23};
        byte[] apnnamedata = mbleLockParamInfo.APN1Name_Value.getBytes();
        ByteBuffer bf = ByteBuffer.allocate(15 + apnnamedata.length);
        bf.put(new byte[]{0x7D, 0x7D});
        bf.put((byte) (15 + apnnamedata.length));
        bf.put(TMPL_Key);
        bf.put(new byte[]{0x50, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x5F, 0x00, 0x00, 0x00, 0x25});
        bf.put(apnnamedata);
        bf.put((byte) 0x23);
        byte[] cmdbytes = bf.array();
        //Log.e(TAG,"TMPL_ReadLockParam_APN:"+CDRYTLock_Utils.bytes2String(cmdbytes));
        writeCharacteristic_TMPL(cmdbytes);
    }
    public static  void TMPL_ReadLockParam_APN() {
        byte[] cmdbytes = new byte[]{0x7D, 0x7D, 0x0F, TMPL_Key, 0x50, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x5F, 0x00, 0x00, 0x00, 0x25, 0x23};
        //Log.e(TAG,"TMPL_ReadLockParam_APN:"+CDRYTLock_Utils.bytes2String(cmdbytes));
        writeCharacteristic_TMPL(cmdbytes);
    }
    public static void TMPL_stopCheckLockSeel() {
        Message msg = new Message();
        msg.what = CLOSE_LOCK;
        blueHandler.sendMessage(msg);
      //  blueHandler.removeCallbacks(mCheckTMPLLockSealRunnable);
    }

    //开锁成功后，不停向锁发送验封指令，判断是否施封
    public static void TMPL_startCheckLockSeal() {
        //if(1==1)return;
        if (!mLockIsOpened) {
            Log.e(TAG, "锁没打开");
            return;
        }
        Message msg = new Message();
        msg.what =UPDATE_STATE;
//        blueHandler.sendMessage(msg);
//        blueHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                TMPL_SendGetLockStateCMD();
//            }
//        }, 1000);
       // blueHandler.removeCallbacks(mCheckTMPLLockSealRunnable);
       // blueHandler.postDelayed(mCheckTMPLLockSealRunnable, 3000);
    }
    //先获取锁的时间
    public static void TMPL_ReadLockUTCTime() {
        byte[] cmdbytes = new byte[]{0x7D, 0x7D, 0x10, TMPL_Key, 0x50, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x5F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x2F};
        writeCharacteristic_TMPL(cmdbytes);
        Log.e(TAG, "Lock 发送TMPL UTC指令.");
    }

    //发送开锁指令
    public static void TMPL_SendOpenLockCMD(int utctime) {
        byte[] utcdata = ByteConvert.convertIntToBytes_BIG_ENDIAN(utctime);
        byte[] cmdbytes = new byte[]{0x7D, 0x7D, 0x10, TMPL_Key, 0x50, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, utcdata[0], utcdata[1], utcdata[2], utcdata[3], 0x30, 0x00, 0x2F};
        writeCharacteristic_TMPL(cmdbytes);
        Log.e(TAG, "Lock 发送TMPL开锁指令.");
    }

    //获取锁的状态
    public static void TMPL_SendGetLockStateCMD() {
        byte[] cmdbytes = new byte[]{0x7D, 0x7D, 0x0F, TMPL_Key, 0x50, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x5F, 0x00, 0x00, 0x00, 0x10, 0x10};//读取固件版本号等参数
        // byte[] cmdbytes=new byte[]{0x7D,0x7D,0x0F,0x00,0x50,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,0x5F,0x00,0x00,0x00,0x13,0x13};
        boolean result = writeCharacteristic_TMPL(cmdbytes);
        Log.e(TAG, "TMPL发送查询锁状态指令。=" + result);
        //syj 循环发送
        Message msg= new Message();
        msg.what =UPDATE_STATE;
        if(blueHandler!=null) {
            blueHandler.sendMessage(msg);
        }
    }
    @SuppressLint("MissingPermission")
    public static boolean writeCharacteristic_TMPL(byte[] bytes) {
        if (mBluetoothGatt == null || write_characteristic == null) {
            return false;
        }
        if (bytes != null) {
            //Log.e(TAG,"加密前："+CDRYTLock_Utils.bytes2String(bytes));
            Encrypt_TMPL(bytes);
            // Log.e(TAG,"加密后："+CDRYTLock_Utils.bytes2String(bytes));
            write_characteristic.setValue(bytes);
            //Log.e(BluetoothLeService.class.getSimpleName(),"bytes:"+HexUtils.bytesToHexString(bytes));


            return mBluetoothGatt.writeCharacteristic(write_characteristic);
        }
        return false;
    }
    //加密
    public static void Encrypt_TMPL(byte[] cmdalldata) {
        byte[] encryptkeytem = new byte[4];
        encryptkeytem[0] = (byte) (TMPL_EncryptKey[0] ^ TMPL_Key);
        encryptkeytem[1] = (byte) (TMPL_EncryptKey[1] ^ TMPL_Key);
        encryptkeytem[2] = (byte) (TMPL_EncryptKey[2] ^ TMPL_Key);
        encryptkeytem[3] = (byte) (TMPL_EncryptKey[3] ^ TMPL_Key);

        TMPL_XOR(cmdalldata);

        for (int i = 4; i < cmdalldata.length - 1; i++) {
            cmdalldata[i] = (byte) (cmdalldata[i] ^ encryptkeytem[i % 4]);
        }

    }

    //异或校验，最后一位是校验位
    public static  void TMPL_XOR(byte[] data) {
        byte checkbyte = 0;
        for (int i = 0; i < data.length - 1; i++) {
            checkbyte = (byte) (data[i] ^ checkbyte);
        }
        data[data.length - 1] = checkbyte;
    }

    //计算电量百分比
    public static  double GetPowerPercent_HHD(double nVol)//4G锁
    {
        //nVol = nVol / 100;
        if ( nVol <= 3 )
        {
            return 0;
        }
        else if ( nVol >= 4.2 )
        {
            return 100;
        }
        double  nBase   = 0;
        double  nMax    = 0;
        double  nMin    = 0;
        double  nMult   = 10;
        if ( nVol < 4.2 && nVol >= 4.06 )
        {
            nBase   = 90;
            nMax    = 4.2;
            nMin    = 4.06;
        }
        else if ( nVol < 4.06 && nVol >= 3.98 )
        {
            nBase   = 80;
            nMax    = 4.06;
            nMin    = 3.98;
        }
        else if ( nVol < 3.98 && nVol >= 3.92 )
        {
            nBase   = 70;
            nMax    = 3.98;
            nMin    = 3.92;
        }
        else if ( nVol < 3.92 && nVol >= 3.87 )
        {
            nBase   = 60;
            nMax    = 3.92;
            nMin    = 3.87;
        }
        else if ( nVol < 3.87 && nVol >= 3.82 )
        {
            nBase   = 50;
            nMax    = 3.87;
            nMin    = 3.82;
        }
        else if ( nVol < 3.82 && nVol >= 3.79 )
        {
            nBase   = 40;
            nMax    = 3.82;
            nMin    = 3.79;
        }
        else if ( nVol < 3.79 && nVol >= 3.77 )
        {
            nBase   = 30;
            nMax    = 3.79;
            nMin    = 3.77;
        }
        else if ( nVol < 3.77 && nVol >= 3.74 )
        {
            nBase   = 20;
            nMax    = 3.77;
            nMin    = 3.74;
        }
        else if ( nVol < 3.74 && nVol >= 3.68 )
        {
            nBase   = 10;
            nMax    = 3.74;
            nMin    = 3.68;
        }
        else if ( nVol < 3.68 && nVol >= 3.45 )
        {
            nBase   = 5;
            nMax    = 3.68;
            nMin    = 3.45;
            nMult   = 5;
        }
        else if ( nVol < 3.45 && nVol >= 3 )
        {
            nBase   = 0;
            nMax    = 3.45;
            nMin    = 3;
            nMult   = 5;
        }
        double  nResult = nBase + nMult * ( nVol - nMin ) / ( nMax - nMin );
        return nResult;
    }

    public static String getCurtimeStr(){

        SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); //设置时间格式

        formatter.setTimeZone(TimeZone.getTimeZone("GMT+08")); //设置时区

        Date curDate = new Date(System.currentTimeMillis()); //获取当前时间

        String timestr = formatter.format(curDate);

        return timestr;//格式转换
    }
}
